import { defineStore } from "pinia";
import { accoutLoginRequest, getUserInfoById, getUserMenusByRoleId } from '@/service/login/login'
import type { IAccount } from '@/types'
import { localCache } from "@/untils/caceh";
import { mapMenusToRoutes } from '@/untils/map-menus'
import router from "@/router";
import { LOGIN_TOKEN } from "@/global/constants";
import type { RouteRecordRaw } from "vue-router";
import useMainStore from "../main/main";
// const LOGIN_TOKEN = 'login/token' // 常量优化

interface ILoginState {
  token: string,
  userInfo: {
    role?: {
      id: number,
      userinfo: any,
      userMenus: any
    }
  }
}

const useLoginStore = defineStore("login", {
  // ILoginState是制定state的类型
  state: (): ILoginState => ({
    token: '',
    userInfo: {},
    userMenus: [],
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      console.log(account, '--e-ee')
      // 1. 账号登录，获取token
      const loginResult = await accoutLoginRequest(account)
      const id = loginResult.data.id
      this.token = loginResult.data.token

      // 2. 进行本地缓存
      localCache.setCache(LOGIN_TOKEN, this.token)

      // 3. 获取登录用户的详细信息（role信息）
      const userInfoResult = await getUserInfoById(id)
      const userInfo = userInfoResult.data
      this.userInfo = userInfo

      // 5. 根据角色请求用户的权限（菜单menus）
      console.log(this.userInfo.role.id, '--menus2222')
      const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
      console.log(userMenusResult, '--menus33333')
      const userMenus = userMenusResult.data
      this.userMenus = userMenus

      // 6. 进行本地缓存
      localCache.setCache(LOGIN_TOKEN, this.token)
      localCache.setCache('userInfo', this.userInfo)
      localCache.setCache('userMenus', this.userMenus)
      // 重要：添加动态路由
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach(route => {
        router.addRoute('main', route)
      });

      // 4. 页面跳转（main页面）
      router.push("/main")
    },

    loadLocalCacheAction() {
      // 用户进行刷新默认加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 重要：添加动态路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach(route => {
          router.addRoute('main', route)
        });
      }
    }
  }
})

export default useLoginStore
